package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.adm.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingyun.gpsinspection.purificationservice.common.activiti.ActivitiConstants;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.adm.BusinessTravelMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.BootstrapSearchBean;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.BusinessTravel;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.adm.TaskLinkIam;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.activiti.base.WorkFlowService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.accessory.BPMService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.BusinessTravelService;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.adm.TaskLinkIamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangsy on 2016/12/19.
 */

public class BusinessTravelServiceImpl implements BusinessTravelService {

    public static final String FLOWKEY = "travel";
    @Autowired
    private BusinessTravelMapper businessTravelMapper;
    @Autowired
    private TaskLinkIamService taskLinkIamService;
    @Autowired
    private BPMService bpmService;
    @Value("#{configProperties['username']}")
    private String bpmUserName;
    @Value("#{configProperties['password']}")
    private String bpmPassword;
    @Autowired
    private WorkFlowService workFlowService;

    /**
     * 根据主键id删除
     *
     * @param businessTravelId
     * @return
     */
    @Override
    public int deleteByPrimaryKey(String businessTravelId) {
        return businessTravelMapper.deleteByPrimaryKey(businessTravelId);
    }

    /**
     * 新增
     *
     * @param record
     * @return
     */
    @Override
    public int insert(BusinessTravel record) {
        return businessTravelMapper.insert(record);
    }
    // TODO: 2017/3/15,0015

    /**
     * 新增
     *
     * @param record
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public synchronized int insertSelective(BusinessTravel record, EmployeeVo employeeVo) throws Exception {
        int count = 0;
        if (record != null) {
            // 保存数据
            count += businessTravelMapper.insertSelective(record);
            //开启流程
            Map map = new HashMap<>();
            List<String> list = new ArrayList<>();
            list.add(record.getApproveId());
            map.put(ActivitiConstants.MANUAL_PERSON, list);
            workFlowService.startProcessInstanceByKey(FLOWKEY, record.getBusinessTravelId(), map, employeeVo.getEmployeeId());
        }
        return count;
    }

    /**
     * 根据id查询信息
     *
     * @param businessTravelId
     * @return
     */
    @Override
    public BusinessTravel selectByPrimaryKey(String businessTravelId) {
        return businessTravelMapper.selectByPrimaryKey(businessTravelId);
    }

    /**
     * 根据id更新
     *
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(BusinessTravel record) {
        return businessTravelMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(BusinessTravel record) {
        return businessTravelMapper.updateByPrimaryKey(record);
    }

    /**
     * 个人申请列表
     *
     * @param businessTravel
     * @return
     */
    @Override
    public JSONObject list(BusinessTravel businessTravel) {
        JSONObject jsonObject = new JSONObject();
        businessTravel.setLimit(businessTravel.getLimit() == null ? 10 : businessTravel.getLimit());
        businessTravel.setOffset(businessTravel.getOffset() == null ? 0 : businessTravel.getOffset());
        //bootstrapSearchBean.setFilterMap(BootstrapUtil.filterStringToMap(bootstrapSearchBean.getFilter()));
        jsonObject.put("total", businessTravelMapper.queryCount(businessTravel));
        jsonObject.put("rows", JSON.toJSON(businessTravelMapper.queryList(businessTravel)));
        return jsonObject;
    }

    /**
     * 代办查找
     *
     * @param bootstrapSearchBean
     * @return
     */
    @Override
    public List<Object> searchByPIId(BootstrapSearchBean bootstrapSearchBean) {
        return businessTravelMapper.searchByPIId(bootstrapSearchBean);
    }

    /**
     * 节点处理
     *
     * @param businessTravel
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int dispose(BusinessTravel businessTravel, EmployeeVo employeeVo) {
        int retCount = 0;
        //处理流程
        if (null != businessTravel) {
            //保存业务数据
            if (null != businessTravel && businessTravel.getStatus() == 1) {
                businessTravel.setStatus(new Short("2"));
            } else if (null != businessTravel && businessTravel.getStatus() == 2) {
                businessTravel.setStatus(new Short("3"));
            }
            retCount += businessTravelMapper.updateByPrimaryKeySelective(businessTravel);
            //控制流程走向
            Map map = new HashMap<>();
            //不管同意驳回都走结束，如果不同意，用户只能新建一个申请。(流程缺陷，后续完善)
            map.put("cond1", 1);
            workFlowService.completeTask(businessTravel.getTaskId(), map, businessTravel.getComments(), employeeVo.getEmployeeId());
        }
        return retCount;
    }

    /**
     * 提交审核
     *
     * @param userName
     * @param pwd
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int sub(BusinessTravel businessTravel, String userName, String pwd) {
        int count = 0;
        //开启流程
        String ret = bpmService.openBPM(1, userName, pwd, null);
        //保存任务环节
        TaskLinkIam taskLink = new TaskLinkIam();
        taskLinkIamService.save(taskLink, ret, (short) 1, businessTravel.getBusinessTravelId(), (short) 1);
        //完成流程
        bpmService.completeTask(taskLink.getTkiid(), userName, pwd, null);
        count += businessTravelMapper.updateByPrimaryKeySelective(businessTravel);
        return count;
    }

    /**
     * 代办总条数
     *
     * @param bootstrapSearchBean
     * @return
     */
    @Override
    public int totalCountByPIId(BootstrapSearchBean bootstrapSearchBean) {
        return businessTravelMapper.totalCountByPIId(bootstrapSearchBean);
    }

    /**
     * 查询我已经审批的
     *
     * @param businessTravel
     * @return
     */
    @Override
    public JSONObject processed(BusinessTravel businessTravel) {
        JSONObject jsonObject = new JSONObject();
        // 分页设置
        businessTravel.setLimit(businessTravel.getLimit() == null ? Integer.valueOf(10) : businessTravel.getLimit());
        businessTravel.setOffset(businessTravel.getOffset() == null ? Integer.valueOf(0) : businessTravel.getOffset());
        // 总条数
        jsonObject.put("total", businessTravelMapper.queryProcessedCount(businessTravel));
        List<BusinessTravel> trainList = businessTravelMapper.queryProcessedList(businessTravel);
        jsonObject.put("rows", JSON.toJSON(trainList));
        return jsonObject;
    }

    /**
     * 查询我的出差待办
     *
     * @param businessTravel
     */
    @Override
    public JSONObject listToDoTask(BusinessTravel businessTravel) {
        JSONObject jsonObject = new JSONObject();
        // 分页设置
        businessTravel.setLimit(businessTravel.getLimit() == null ? Integer.valueOf(10) : businessTravel.getLimit());
        businessTravel.setOffset(businessTravel.getOffset() == null ? Integer.valueOf(0) : businessTravel.getOffset());
        // 总条数
        jsonObject.put("total", businessTravelMapper.queryToDoCount(businessTravel));
        List<BusinessTravel> trainList = businessTravelMapper.queryToDoList(businessTravel);
        jsonObject.put("rows", JSON.toJSON(trainList));
        return jsonObject;
    }
}
